<?php
class UserController extends Nguyen_Controller_Action{
	public function init(){
		$this->loadTemplate('login');
	}
	public function indexAction(){ 
	}	
	public function loginAction(){ 
	$this->view->headTitle('Đăng Nhập',true);
	    if ($this->_request->isPost()) {
	        if ($this->_request->getParam('username')&&$this->_request->getParam('password')){
	        	
		        //1.Goi ket noi voi Zend Db
		        $db = Zend_Registry::get('vicdbsystem');
		        //$db = Zend_Db::factory($dbOption['adapter'],$dbOption['params']);
		        //2. Khoi tao Zend Autho
		        $auth = Zend_Auth::getInstance ();
		
		        //3. Khai bao bang va 2 cot se su dung so sanh trong qua tronh login
		        $authAdapter = new Zend_Auth_Adapter_DbTable($db);
		        $authAdapter->setTableName('user')
		                ->setIdentityColumn('username')
		                ->setCredentialColumn('password');
		
		        //4. Lay gia tri duoc gui qua tu FORM
		        $uname = $this->_request->getParam('username');
		        $paswd = $this->_request->getParam('password');
		
		        //5. Dua vao so sanh voi du lieu khai bao o muc 3
		        $authAdapter->setIdentity($uname);
		        $authAdapter->setCredential(md5($paswd));
		
		        //6. Kiem tra trang thai cua user neu status = 1 moi duoc login
		        $select = $authAdapter->getDbSelect();
		        $select->where('status = 1');
		        //7. Lay ket qua truy van
		        
		        $result = $auth->authenticate($authAdapter);
				
		        $flag = false;
		        if ($result->isValid()) {
		            //8. Lay nhung du lieu can thiet trong bang users neu login thanh cong				
		            $data = $authAdapter->getResultRowObject(null, array('password'));
		
		            //9. Luu  nhung du lieu cua member vao session
		            $auth->getStorage()->write($data);		            
		            $flag = true;
		        }
		        if ($flag == true) {
    				$infoUser = $auth->getIdentity();
		        	if($infoUser->type == 1 || $infoUser->type == 2 || $infoUser->type == 3){
		           	 $this->_redirect('/administrator');
		    		}else {
		    			$this->_redirect('/');
		    		}
		        }
	        	if ($flag == false) {
		            $this->_redirect('/administrator/user/login');
		        }
	        }
	        else{
	        	$this->_redirect('/administrator/user/login');}
	    }
	}	
	public function logoutAction() {
    	$this->_helper->viewRenderer->setNoRender();
    	$this->_helper->layout->disableLayout();
	    $auth = Zend_Auth::getInstance();
	    $auth->clearIdentity();
	    $this->_redirect('/user/login');
	}
}